package com.igoal.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.igoal.dto.NewsDTO;
import com.igoal.dto.UserDTO;
import com.igoal.service.CommentService;
import com.igoal.service.MessageManager;
import com.igoal.service.NewsManager;
import com.igoal.service.UserManagerExt;
import com.igoal.utils.ConvertUtils;
import com.igoal.web.model.BaseModel;
import com.igoal.web.model.NewsDetailModel;

@Controller
@RequestMapping("/newsDetails.html")
public class NewsDetailsController extends BaseController {
	private NewsManager newsManager;
	private CommentService commentService;
	
	@Autowired
	public void setCommentService(CommentService commentService) {
		this.commentService = commentService;
	}

	@Autowired
	public void setNewsManager(NewsManager newsManager) {
		this.newsManager = newsManager;
	}
	
	@Autowired
	public void setUserManagerExt(UserManagerExt userManagerExt) {
		this.userManagerExt = userManagerExt;
	}
	
	@Autowired
	public void setMessageManager(MessageManager messageManager) {
		this.messageManager = messageManager;
	}
	
	public String getViewPrefix() {
		return BaseControllerDelegate.DEFAULT_VIEW_PREFIX;
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public String show(ModelMap modelMap, HttpServletRequest request){
		NewsDetailModel model = new NewsDetailModel();

		initTopPage(model, request);
		initLeftPage(model, request);
		initRightPage(model, request);
		
		applyModel(modelMap, model);		
		return getViewPrefix() + "newsDetails";
	}

	public void initTopPage(BaseModel baseModel, HttpServletRequest request) {
		NewsDetailModel model = (NewsDetailModel) baseModel;
		UserDTO sessionUser = null;
		if(isLoginUser())
			sessionUser = getUserSession();
		
		initTopZone(sessionUser, model);
		model.setRandomNews(newsManager.getRandomNews());
	}

	public void initRightPage(BaseModel model, HttpServletRequest request) {
		UserDTO sessionUser = null;
		if(isLoginUser())
			sessionUser = getUserSession();
		initRightZone(sessionUser, model);
	}

	public void initLeftPage(BaseModel baseModel, HttpServletRequest request) {
		NewsDetailModel model = (NewsDetailModel) baseModel;
		String entryId = request.getParameter("id");
		Long id = ConvertUtils.toLong(entryId, -1L);
		if(id > 0L){
			NewsDTO news = newsManager.loadNews(id);
			model.setNews(news);
		}
	}

}
